import 'dart:async';
import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

///

/// Description: 代码文件说明，markdown 格式
///

class AccountPasswordInputSection extends StatelessWidget {
  final String account;
  final FocusNode accountNode;
  final String password;
  final FocusNode passwordNode;
  final ValueChanged<String> onAccountChanged;
  final ValueChanged<String> onAccountSubmitted;
  final ValueChanged<String> onPasswordChanged;
  final ValueChanged<String> onPasswordSubmitted;
  final bool autofocus;

  const AccountPasswordInputSection({
    Key? key,
    required this.account,
    required this.accountNode,
    required this.password,
    required this.passwordNode,
    required this.onAccountChanged,
    required this.onAccountSubmitted,
    required this.onPasswordChanged,
    required this.onPasswordSubmitted,
    this.autofocus = true,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        UnderLineInputField(
          value: account,
          focusNode: accountNode,
          hintText: '请输入账号',
          autofocus: autofocus,
          keyboardType: TextInputType.text,
          onChanged: onAccountChanged,
          onSubmitted: onAccountSubmitted,
          inputAction: TextInputAction.next,
          enableInteractiveSelection: false,
        ),
        SizedBox(height: 20),
        UnderLineInputField(
          value: password,
          focusNode: passwordNode,
          hintText: '请输入密码',
          obscureText: true,
          keyboardType: TextInputType.text,
          onChanged: onPasswordChanged,
          onSubmitted: onPasswordSubmitted,
          inputAction: TextInputAction.done,
          enableInteractiveSelection: false,
        ),
      ],
    );
  }
}

class MobileCodeInputSection extends StatelessWidget {
  final String mobile;
  final String? mobileHint;
  final String code;

  ///验证码发送
  final Future<bool> Function() onSendCode;

  ///手机号输入
  final ValueChanged<String> onMobileChanged;

  ///验证码输入
  final ValueChanged<String> onCodeChanged;

  ///输入间距
  final double space;

  ///焦点
  final bool autofocus;
  final FocusNode? mobileFocusNode;
  final FocusNode? codeFocusNode;

  /// 紧凑样式
  final bool isDense;

  const MobileCodeInputSection({
    Key? key,
    required this.mobile,
    this.mobileHint,
    required this.code,
    required this.onSendCode,
    required this.onMobileChanged,
    required this.onCodeChanged,
    this.space = 20,
    this.autofocus = true,
    this.mobileFocusNode,
    this.codeFocusNode,
    this.isDense = false,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    String mobileValue = mobile;
    String codeValue = code;
    return StatefulBuilder(
      builder: (context, setState) {
        return Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            UnderLineInputField(
              value: mobileValue,
              hintText: mobileHint ?? '请输入手机号',
              autofocus: autofocus,
              isDense: isDense,
              focusNode: mobileFocusNode,
              keyboardType: TextInputType.phone,
              onChanged: (mobile) {
                mobileValue = mobile;
                onMobileChanged(mobile);
                setState(() {});
              },
              inputAction: TextInputAction.next,
            ),
            SizedBox(height: space),
            UnderLineInputField(
              value: codeValue,
              hintText: '请输入验证码',
              isDense: isDense,
              suffix: CounterDownButton(
                onSendCode: onSendCode,
                enabled: mobileValue.length == 11,
                isDense: isDense,
              ),
              keyboardType: TextInputType.number,
              onChanged: onCodeChanged,
              inputAction: TextInputAction.done,
              focusNode: codeFocusNode,
            ),
          ],
        );
      },
    );
  }
}

class _CDB {
  /// 是否可以获取验证码  手机号11位时才可以
  bool enableGetSmsCode = false;

  _CDB(this.enableGetSmsCode);
}

class CounterDownButton extends StatefulWidget {
  final Future<bool> Function() onSendCode;
  final bool enabled;
  final bool isDense;

  const CounterDownButton(
      {Key? key,
      required this.onSendCode,
      this.enabled = true,
      this.isDense = false})
      : super(key: key);

  @override
  _CounterDownButtonState createState() => _CounterDownButtonState();
}

class _CounterDownButtonState extends State<CounterDownButton> {
  var _second = 0;
  Timer? _timer;
  var _havSend = false;

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var color = Color(0xFF006FFF);
    if (!widget.enabled) {
      color = Color(0xFFCECED1);
    } else if (_second == 0) {
      color = Color(0xFF006FFF);
    } else {
      color = Color(0xFFCECED1);
    }
    return FilledButton(
      onPressed: (_second == 0 && widget.enabled)
          ? () async {
              var success = await widget.onSendCode();
              if (success) {
                _havSend = true;
                setState(() {
                  _second = 59;
                });
                _timer = Timer.periodic(Duration(seconds: 1), (timer) {
                  _second = _second - 1;
                  if (_second <= 0) {
                    timer.cancel();
                    _timer = null;
                    setState(() {});
                  } else {
                    setState(() {});
                  }
                });
              }
            }
          : null,
      child: Container(
        width: 80,
        padding: EdgeInsets.only(
          left: 10,
          right: 0,
          top: 8,
          bottom: widget.isDense ? 4 : 8,
        ),
        // alignment: widget.isDense ? Alignment.bottomRight : Alignment.center,
        alignment: Alignment.bottomRight,
        child: Text(
          _second == 0
              ? (_havSend ? '重新发送' : '获取验证码')
              : kIsWeb
                  ? '$_second s'
                  : '重新发送($_second)',
          style: TextStyle(
            fontSize: 14,
            color: color,
          ),
        ),
      ),
    );
  }
}

class UnderLineInputField extends StatelessWidget {
  final String? hintText;
  final String value;
  final Widget? prefix;
  final Widget? suffix;
  final TextInputType? keyboardType;
  final ValueChanged<String> onChanged;
  final ValueChanged<String>? onSubmitted;
  final bool obscureText;
  final bool autofocus;
  final bool enableInteractiveSelection;

  final FocusNode? focusNode;
  final TextInputAction? inputAction;

  final bool isDense;
  final List<TextInputFormatter>? inputFormatters;

  const UnderLineInputField({
    Key? key,
    this.hintText,
    required this.value,
    this.prefix,
    this.suffix,
    this.keyboardType,
    required this.onChanged,
    this.focusNode,
    this.inputAction,
    this.onSubmitted,
    this.obscureText = false,
    this.autofocus = false,
    this.enableInteractiveSelection = true,
    this.isDense = false,
    this.inputFormatters,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    String valueText = value;
    var controller = TextEditingController.fromValue(
      TextEditingValue(
        text: valueText,
        selection: TextSelection.fromPosition(
          TextPosition(
            affinity: TextAffinity.downstream,
            offset: valueText.length,
          ),
        ),
      ),
    );
    return StatefulBuilder(
      builder: (context, setState) {
        return Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Row(
              crossAxisAlignment:
                  isDense ? CrossAxisAlignment.end : CrossAxisAlignment.center,
              children: [
                Container(
                  constraints: BoxConstraints(maxHeight: 37),
                  child: prefix ?? SizedBox.shrink(),
                ),
                Expanded(
                  child: TextField(
                    controller: controller,
                    autofocus: autofocus,
                    obscureText: obscureText,
                    enableInteractiveSelection: enableInteractiveSelection,
                    focusNode: focusNode,
                    textInputAction: inputAction,
                    keyboardType: keyboardType,
                    onChanged: (value) {
                      valueText = value;
                      onChanged(value);
                      setState(() {});
                    },
                    inputFormatters: inputFormatters,
                    onSubmitted: onSubmitted,
                    decoration: InputDecoration(
                      isDense: true,
                      hintText: hintText,
                      hintStyle: TextStyle(
                        fontSize: 14,
                        color: Color(0x5C787880),
                      ),
                      border: InputBorder.none,
                      enabledBorder: InputBorder.none,
                      focusedBorder: InputBorder.none,
                      suffixIcon: (valueText.isNotEmpty == true)
                          ? InkWell(
                              onTap: () {
                                controller.clear();
                                onChanged('');
                                valueText = '';
                                setState(() {});
                              },
                              child: Container(
                                padding: EdgeInsets.symmetric(
                                    horizontal: 10, vertical: 6),
                                child: Icon(Icons.close),
                              ),
                            )
                          : SizedBox.shrink(),
                      suffixIconConstraints: BoxConstraints(maxHeight: 37),
                    ),
                  ),
                ),
                Container(
                  constraints: BoxConstraints(maxHeight: 37),
                  child: suffix == null
                      ? SizedBox.shrink()
                      : Padding(
                          padding: const EdgeInsets.only(left: 8),
                          child: suffix!,
                        ),
                ),
              ],
            ),
            Divider(height: 1, color: Colors.black26),
          ],
        );
      },
    );
  }
}
